﻿using IapService.Entity;
using NHibernate.Criterion;

namespace IapService.Data
{
    public class InstanceFavoriteData : Data<InstanceFavorite>
    {
        public InstanceFavorite Get(int id)
        {
            InstanceFavorite item;
            using (var session = Session)
            {
                item = session.Get<InstanceFavorite>(id);
            }
            return item;
        }

        public InstanceFavorite GetByFavoriteId(int favoriteId)
        {
            InstanceFavorite item;
            using (var session = Session)
            {
                item = session.CreateCriteria<InstanceFavorite>()
                    .Add(Restrictions.Eq("Favorite.Id", favoriteId))
                    .UniqueResult<InstanceFavorite>()
                    ;
            }
            return item;
        }

        public new InstanceFavorite Save(InstanceFavorite item)
        {
            var needSaveInstanceFavorite = item.Id == 0 && item.Favorite.Id == 0;
            var favorite = item.Favorite;
            var favoriteData = new FavoriteData();
            favoriteData.SaveFromInstanceFavorite(favorite);

            var sample = favorite.Sample;
            var sampleData = new SampleData();
            sampleData.SaveFromFavorite(sample);

            if (!needSaveInstanceFavorite) return item;

            using (var session = Session)
            {
                if(item.Id == 0)
                {
                    var attemptGet = session.CreateCriteria<InstanceFavorite>()
                        .Add(Restrictions.Eq("Favorite.Id", item.Favorite.Id))
                        .UniqueResult<InstanceFavorite>()
                        ;
                    if (attemptGet != null && attemptGet.Id > 0)
                    {
                        item.Id = attemptGet.Id;
                    }
                }
                session.SaveOrUpdate(item);
                session.Flush();
            }
            return item;
        }
    }
}